//
//  ViewController.swift
//  textview
//
//  Created by ap0stader on 2023/10/19.
//

import UIKit

class ViewController: UIViewController,  UITextViewDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func dismissKeyboard(_ sender: UITapGestureRecognizer) {
        paragraphTextView.resignFirstResponder()
        keywordTextField.resignFirstResponder()
    }
    
    @IBOutlet var paragraphTextView: UITextView!
    
    @IBOutlet var keywordTextField: UITextField!
    
    @IBOutlet var resultLabel: UILabel!
    
    var keyword: String = " "
    
    var paragraph: String = " "
    
    func searchKeyword(theString : String, theSubS: String) -> Int {
        return theString.components(separatedBy: theSubS).count - 1
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if (text == "\n") {
            keywordTextField.becomeFirstResponder()
            return false
        } else {
            return true
        }
    }
    
    @IBAction func textFieldChanged(_ sender: Any) {
        keyword = keywordTextField.text!
        paragraph = paragraphTextView.text!
        let counts = searchKeyword(theString: paragraph, theSubS: keyword)
        resultLabel.text = "\(counts)"
    }
}

